package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Relation;
import com.example.mapper.RelationMapper;
import com.example.mapper.UserMapper;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.utils.MD5Utils;
import com.example.utils.UserDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RelationMapper relationMapper;
    @Override
    @Transactional
    public UserDTO login(UserDTO userDTO) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", userDTO.getAccount()).eq("password",userDTO.getPassword());
        User user = userMapper.selectOne(wrapper);
        if (user != null){
            BeanUtil.copyProperties(user,userDTO,true);
            Integer roleid = user.getRoleid();
            List<Relation> roleRelation = getRoleMenus(roleid);
            userDTO.setRelationList(roleRelation);
            return userDTO;
        }else {
            return null;
        }
    }
    //获取用户数量
    @Override
    public List<User> getUserCount() {
        return userMapper.getUserCount();
    }


    /**
     *
     * 获取当前角色的菜单列表
     * **/
    private List<Relation> getRoleMenus(Integer roleid){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("roleid",roleid);
        //获取到当前角色的所有菜单
        List<Relation> roleRelation = relationMapper.selectList(queryWrapper);
        return  roleRelation;
    }
}
